package com.guit.hrms.controller;

import com.guit.hrms.mapper.RoleMapper;
import com.guit.hrms.po.Article;
import com.guit.hrms.po.Permission;
import com.guit.hrms.po.Role;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.service.ArticleService;
import com.guit.hrms.service.QueryService;
import com.guit.hrms.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 文章管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/articles")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private QueryService queryService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private HttpServletRequest request;  // 注入 HttpServletRequest
    
    /**
     * 获取所有文章
     */
    @GetMapping
    public Result getAllArticles() {
        try {
            log.info("开始获取所有文章");
            List<Article> articles = articleService.getAllArticles();
            log.info("获取文章列表成功，数量: {}", articles.size());
            return Result.success(articles);
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            return Result.error("获取文章列表失败");
        }
    }

    /**
     * 管理员获取所有文章
     */
    @GetMapping("/admin")
    public Result getAdminArticles() {
        try {
            log.info("管理员开始获取文章");
            Map<String,Object> map = ThreadLocalUtil.get();
            String employeeId = (String) map.get("employeeId");
            if (employeeId == null) {
                return Result.error("请先登录");
            }
            Role role = queryService.getRoleById(employeeId);
            List<Permission> permissions = roleMapper.queryPermissionByRoleId(role.getId());
            System.out.println("获取管理员所有权限"+ permissions);
            boolean hasArticleManagePermission = permissions.stream()
                    .anyMatch(p -> "article-management".equals(p.getName()));
            if (hasArticleManagePermission){
                List<Article> articles = articleService.getAllArticlesWithToken();
                return Result.success(articles);
            }
            return Result.error("没有权限查看文章");
        }catch (Exception e){
            log.error("管理员获取文章列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID获取文章
     */
    @GetMapping("/{id}")
    public Result getArticleById(@PathVariable Long id) {
        try {
            Article article = articleService.getArticleById(id);
            if (article == null) {
                return Result.error("文章不存在");
            }
            articleService.incrementViewCount(id);
            return Result.success(article);
        } catch (Exception e) {
            log.error("获取文章详情失败", e);
            return Result.error("获取文章详情失败");
        }
    }
    
    /**
     * 根据类型获取文章列表
     */
    @GetMapping("/type/{type}")
    public Result getArticlesByType(@PathVariable Integer type) {
        try {
            List<Article> articles = articleService.getArticlesByType(type);
            return Result.success(articles);
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            return Result.error("获取文章列表失败");
        }
    }
    
    /**
     * 创建文章（需要验证身份）
     */
    @PostMapping("/create")
    public Result createArticle(@RequestBody Article article) {
        try {
            log.info("开始创建文章: {}", article);
            
            // 获取当前登录用户信息
            Map<String, Object> map = ThreadLocalUtil.get();
            log.info("ThreadLocal中的用户信息: {}", map);
            
            if (map == null) {
                log.error("用户未登录");
                return Result.error("用户未登录");
            }
            
            // 直接从 map 中获取，不需要强制类型转换
            String employeeId = map.get("employeeId").toString();
            String username = map.get("username").toString();
            log.info("当前用户: {}, {}", employeeId, username);
            
            // 参数校验
            if (article.getTitle() == null || article.getTitle().trim().isEmpty()) {
                return Result.error("标题不能为空");
            }
            if (article.getContent() == null || article.getContent().trim().isEmpty()) {
                return Result.error("内容不能为空");
            }
            if (article.getArticleType() == null) {
                return Result.error("文章类型不能为空");
            }
            
            // 设置作者和编辑者
            article.setAuthor(username);
            article.setEditor(username);
            
            Article created = articleService.createArticle(article);
            log.info("文章创建成功: {}", created);
            return Result.success(created);
        } catch (Exception e) {
            log.error("创建文章失败", e);
            return Result.error("创建文章失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新文章（需要验证身份）
     */
    @PutMapping("/{id}/update")
    public Result updateArticle(@PathVariable Long id, @RequestBody Article article) {
        try {
            // 获取当前登录用户信息
            Map<String, Object> map = ThreadLocalUtil.get();
            String username = (String) map.get("username");
            
            // 检查是否有权限修改
            Article existing = articleService.getArticleById(id);
            if (existing == null) {
                return Result.error("文章不存在");
            }
            
            // 设置更新信息
            article.setId(id);
            article.setEditor(username);
            
            Article updated = articleService.updateArticle(article);
            return Result.success(updated);
        } catch (Exception e) {
            log.error("更新文章失败", e);
            return Result.error("更新文章失败");
        }
    }
    
    /**
     * 删除文章（需要验证身份）
     */
    @DeleteMapping("/{id}/delete")
    public Result deleteArticle(@PathVariable Long id) {
        try {
            // 获取当前登录用户信息
            Map<String, Object> map = ThreadLocalUtil.get();
            
            // 检查是否有权限删除
            Article existing = articleService.getArticleById(id);
            if (existing == null) {
                return Result.error("文章不存在");
            }

            boolean success = articleService.deleteArticle(id);
            return success ? Result.success() : Result.error("删除文章失败");
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return Result.error("删除文章失败");
        }
    }

    /**
     * 恢复文章
     */
    @PutMapping("/{id}/restore")
    public Result restoreArticle(@PathVariable Long id) {
        try{
            log.info("管理员尝试恢复文章");
            Map<String,Object> map = ThreadLocalUtil.get();
            String employeeId = (String) map.get("employeeId");
            if (employeeId == null) {
                return Result.error("请先登录");
            }
            Role role = queryService.getRoleById(employeeId);
            List<Permission> permissions = roleMapper.queryPermissionByRoleId(role.getId());
            System.out.println("获取管理员所有权限"+ permissions);
            boolean hasArticleManagePermission = permissions.stream()
                    .anyMatch(p -> "article-management".equals(p.getName()));
            int isSuccess;
            if (hasArticleManagePermission){
                articleService.restoreArticle(id);
                isSuccess = articleService.restoreArticle(id);
                if (isSuccess == 1)
                {
                    return Result.success("恢复文章成功");
                }
                return Result.error("恢复文章失败");
            }
            return Result.error("没有恢复文章的权限");
        }catch (Exception e){
            log.error("恢复文章失败");
            return Result.error("恢复文章失败");
        }
    }

    /**
     * 硬删除文章（需要验证身份）
     * 会同时删除文章及其关联的所有附件
     */
    @DeleteMapping("/{id}/hard-delete")
    public Result hardDeleteArticle(@PathVariable Long id) {
        try {
            // 获取当前登录用户信息
            Map<String, Object> map = ThreadLocalUtil.get();
            if (map == null) {
                log.error("用户未登录");
                return Result.error("用户未登录");
            }
            
            // 检查是否有权限删除
            Article existing = articleService.getArticleById(id);
            if (existing == null) {
                return Result.error("文章不存在");
            }
            
            // 执行硬删除
            boolean success = articleService.hardDeleteArticle(id);
            log.info("硬删除文章结果: {}", success);
            return success ? Result.success("文章及其附件已永久删除") : Result.error("删除文章失败");
        } catch (Exception e) {
            log.error("硬删除文章失败", e);
            return Result.error("删除文章失败: " + e.getMessage());
        }
    }
} 